<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceName">
              <a-input v-model="model.deviceName" placeholder="请输入设备名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="设备ID" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceId">
              <a-input v-model="model.deviceId" placeholder="请输入设备ID" @blur="deviceIdChange"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="产品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceProductId">
              <a-input v-model="model.deviceProductId" placeholder="请输入产品"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceTypeId">
              <j-device-tree-select ref="treeSelect" v-model="model.deviceTypeId" placeholder="请选择型号"
                                    dict="view_device_brand,name,id" pidValue="0"
                                    :treeData="formatTreeData"
                                    @change="deviceTypeChange">
              </j-device-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.deviceBrandId" placeholder="请输入品牌" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="在线状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceStatus">
              <j-dict-select-tag type="list" v-model="model.deviceStatus" dictCode="device_online_status"
                                 placeholder="请选择在线状态" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="使用状态"  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceUseStatus">
              <j-dict-select-tag type="list" v-model="model.deviceUseStatus" dictCode="device_use_status" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="采购部门" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="devicePurchaseDeptId">
              <j-select-depart v-model="model.devicePurchaseDeptId" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="采购人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="devicePurchaseUserId">
              <j-select-user-by-dep v-model="model.devicePurchaseUserId" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="采购日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="devicePurchaseDate">
              <j-date placeholder="请选择采购日期" v-model="model.devicePurchaseDate" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="使用部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceUseDeptId">
              <j-select-depart v-model="model.deviceUseDeptId" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="使用负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceUseUserId">
              <j-select-user-by-dep v-model="model.deviceUseUserId" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="购置方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="acquisitionMethod">
              <a-input v-model="model.acquisitionMethod" placeholder="请输入购置方式"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="资产负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="assetBelong">
              <a-input v-model="model.assetBelong" placeholder="请输入资产负责人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="资产净值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="assetNetValue">
              <a-input v-model="model.assetNetValue" placeholder="请输入资产净值"></a-input>
            </a-form-model-item>
          </a-col>


          <a-col :span="8">
            <a-form-model-item label="资产原值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="assetOriginalValue">
              <a-input v-model="model.assetOriginalValue" placeholder="请输入资产原值"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="位号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="tags">
              <a-input v-model="model.tags" placeholder="请输入位号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="设备位置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="devicePosition">
              <a-input v-model="model.devicePosition" placeholder="请输入设备位置"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row class="images">
          <a-col :span="8">
            <a-form-model-item label="设备图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceImages">
              <j-image-upload isMultiple v-model="model.deviceImages"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="设备说明书" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceManual">
              <j-upload-device v-model="model.deviceManual"></j-upload-device>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="设备图纸" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceDrawings">
              <j-image-upload isMultiple v-model="model.deviceDrawings"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceRemarks">
              <a-textarea v-model="model.deviceRemarks" rows="2" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
          <a-col :span="23">
            <a-form-model-item label="子设备" :labelCol="labelCol1" :wrapperCol="wrapperCol1" prop="eneDeviceLowers">
              <div class='mark-infos'>
                <a-button class="editable-add-btn" type="primary" shape="circle" icon="plus" style="margin-right: 15px"
                          @click="handleAdd"></a-button>
                <a-table ref="markTable" size="middle" bordered :scroll="{y: '30vh',x: 1500}" rowKey="id"
                         :columns="columns" :dataSource="model.eneDeviceLowers" :pagination="false" :loading="loading"
                         class="j-table-force-nowrap1">
                  <template
                    v-for="col in ['deviceName', 'deviceId', 'deviceProductId', 'deviceTypeId', 'deviceBrandId','devicePurchaseDate','acquisitionMethod','devicePurchaseDeptId','devicePurchaseUserId']"
                    :slot="col" slot-scope="text, record, index">
                    <div :key="col">
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].deviceName'"
                                         :rules="[{ required: true, message: '请输入子设备名称', trigger: 'blur' }]"
                                         v-if="col==='deviceName'">
                        <a-input v-model="record.deviceName" placeholder="请输入设备名称"></a-input>
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].deviceId'"
                                         :rules="[{ required: true, message: '请输入子设备名称', trigger: 'blur' }]"
                                         v-if="col==='deviceId'">
                        <a-input v-model="record.deviceId" placeholder="请输入设备ID" @blur="deviceIdChange"></a-input>
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].deviceProductId'"
                                         v-if="col==='deviceProductId'">
                        <a-input v-model="record.deviceProductId" placeholder="请输入产品"></a-input>
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].deviceTypeId'"
                                         v-if="col==='deviceTypeId'">
                        <j-device-tree-select ref="treeSelect" v-model="record.deviceTypeId" placeholder="请选择型号"
                                              dict="view_device_brand,name,id" pidValue="0"
                                              :treeData="formatTreeData"
                                              @change="lowerDeviceTypeChange(record)"
                                              style="height: 100%"
                        >
                        </j-device-tree-select>
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].deviceBrandId'"
                                         v-if="col==='deviceBrandId'">
                        <j-search-select-tag v-model="record.deviceBrandId" dict="ene_device_brand,brand_name,id"
                                             disabled />
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].devicePurchaseDeptId'"
                                         v-if="col==='devicePurchaseDeptId'">
                        <j-select-depart v-model="record.devicePurchaseDeptId" :multi="true" />
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].devicePurchaseUserId'"
                                         v-if="col==='devicePurchaseUserId'">
                        <j-select-user-by-dep v-model="record.devicePurchaseUserId" :multi="true" />
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].devicePurchaseDate'"
                                         v-if="col==='devicePurchaseDate'">
                        <j-date placeholder="请选择采购日期" v-model="record.devicePurchaseDate" :show-time="true"
                                date-format="YYYY-MM-DD HH:mm:ss" style="width: 50px" />
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].acquisitionMethod'"
                                         v-if="col==='acquisitionMethod'">
                        <a-input v-model="record.acquisitionMethod" placeholder="请输入购置方式"></a-input>
                      </a-form-model-item>
                      <a-form-model-item :prop="'eneDeviceLowers[' + index + '].tags'"
                                         v-if="col==='tags'">
                        <a-input v-model="record.tags" placeholder="请输入位号"></a-input>
                      </a-form-model-item>
                    </div>
                  </template>
                  <template slot="action" slot-scope="text, record, index">
                    <a-popconfirm title="确定删除吗?" @confirm="() => onDelete(record.id,index)">
                      <a-button type="primary" shape="circle" icon="minus"></a-button>
                    </a-popconfirm>
                  </template>
                </a-table>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="23" style="margin-left: 40px">
            <a-tabs v-model="activeKey" @change="handleChangeTabs">
              <a-tab-pane tab="扩展技术参数" :key="refKeys[0]" :forceRender="true">
                <a-row :gutter="24" style="margin-bottom: 10px;">
                  <a-col :span="24">
                    <a-button @click="initExtendedTechnicalParameters" icon="plus">新增</a-button>
                  </a-col>
                </a-row>
                <j-vxe-table
                  keep-source
                  :ref="refKeys[0]"
                  :loading="extendedTechnicalParametersTable.loading"
                  :columns="extendedTechnicalParametersTable.columns"
                  :dataSource="extendedTechnicalParametersTable.dataSource"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="true"
                  :toolbar="true"
                  :toolbarConfig="{ slot: ['suffix'], btn: ['clearSelection'] }"
                >
                  <template #action="props">
                    <a-popconfirm title="确定删除吗？" @confirm="handleDeleteRow(props)">
                      <a>删除</a>
                    </a-popconfirm>
                  </template>
                </j-vxe-table>
              </a-tab-pane>
            </a-tabs>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getAction, httpAction, iotHttpAction } from '@/api/manage'
import JUploadDevice from '@comp/jeecg/JUploadDevice.vue'
import JDeviceTreeSelect from '@comp/jeecg/JDeviceTreeSelect.vue'
import SelectProcurementModal from '@views/business/procurement/modules/SelectProcurementModal.vue'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'

export default {
  name: 'EneDeviceForm',
  components: { SelectProcurementModal, JDeviceTreeSelect, JUploadDevice },
  mixins: [JVxeTableModelMixin],
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      count: 0,
      dataSource: [],  //子设备数据
      model: {
        deviceUseStatus:1,
        eneDeviceLowers: [],
        extendedTechnicalParameters: []
      },
      treeData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol1: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol1: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      loading: false,
      validatorRules: {
        deviceName: [{ required: true, message: '请输入设备名称!' }],
        deviceUseStatus:  [{ required: true, message: '请选择设备状态!' }],
        deviceId: [{ required: true, message: '请输入设备ID!' }],
        // deviceWorkshopId: [{ required: true, message: '请选择用能单位!' }],
        deviceTypeId: [{ required: true, message: '请输入型号!' }]
      },
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '子设备名称',
          align: 'center',
          dataIndex: 'deviceName',
          width: 75,
          scopedSlots: { customRender: 'deviceName' }
        },
        {
          title: '子设备ID',
          align: 'center',
          dataIndex: 'deviceId',
          width: 75,
          scopedSlots: { customRender: 'deviceId' }
        },
        {
          title: '产品',
          align: 'center',
          dataIndex: 'deviceProductId',
          width: 75,
          scopedSlots: { customRender: 'deviceProductId' }
        },
        {
          title: '型号',
          align: 'center',
          dataIndex: 'deviceTypeId',
          width: 100,
          scopedSlots: { customRender: 'deviceTypeId' }
        },
        {
          title: '品牌',
          align: 'center',
          dataIndex: 'deviceBrandId_dictText',
          width: 80,
          scopedSlots: { customRender: 'deviceBrandId' }
        },
        {
          title: '采购部门',
          align: 'center',
          dataIndex: 'devicePurchaseDeptId',
          width: 80,
          scopedSlots: { customRender: 'devicePurchaseDeptId' }
        },
        {
          title: '采购人',
          align: 'center',
          dataIndex: 'devicePurchaseUserId',
          width: 150,
          scopedSlots: { customRender: 'devicePurchaseUserId' }
        },
        {
          title: '采购日期',
          align: 'center',
          dataIndex: 'devicePurchaseDate',
          width: 150,
          scopedSlots: { customRender: 'devicePurchaseDate' }
        },
        {
          title: '购置方式',
          align: 'center',
          dataIndex: 'acquisitionMethod',
          width: 80,
          scopedSlots: { customRender: 'acquisitionMethod' }
        },
        {
          title: '',
          dataIndex: 'action',
          align: 'center',
          width: 50,
          scopedSlots: { customRender: 'action' }
        }
      ],
      activeKey: 'extendedTechnicalParameters',
      refKeys: ['extendedTechnicalParameters'],
      extendedTechnicalParametersTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '项目',
            key: 'project',
            type: JVXETypes.select,
            width: '150px',
            defaultValue:'',
            options: [
              { value: '位号', text: '位号' },
              { value: '全容积', text: '全容积' },
              { value: '工作介质', text: '工作介质' },
              { value: '设计压力', text: '设计压力' }
            ]
          },
          {
            title: '值',
            key: 'value',
            type: JVXETypes.input,
            width: '150px',
            defaultValue:''
          },
          {
            title: '操作',
            key: 'actions',
            width: '150px',
            align: 'center',
            fixed: 'right',
            type: JVXETypes.slot,
            slotName: 'action'
          }
        ]
      },
      url: {
        add: '/device/eneDevice/add',
        edit: '/device/eneDevice/edit',
        queryById: '/device/eneDevice/queryById',
        typeQueryById: '/device/eneDeviceType/queryById',
        getBrandId: '/device/eneDevice/getBrandId'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    formatTreeData() {
      return this.treeData.map(node => ({
        ...node,
        selectable: node.parentId !== '0',
        value: node.key
      }))
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  mounted() {
  },
  methods: {
    // 新增：初始化扩展技术参数
    initExtendedTechnicalParameters() {
      // 在现有数据末尾添加新行（空数据）
      this.extendedTechnicalParametersTable.dataSource = [
        ...this.extendedTechnicalParametersTable.dataSource,
        { project: '', value: '' }
      ];
    },
    // 新增：删除一行参数
    handleDeleteRow({ row }) {
      const index = this.extendedTechnicalParametersTable.dataSource.indexOf(row)
      if (index > -1) {
        this.extendedTechnicalParametersTable.dataSource.splice(index, 1)
      }
    },
    onDelete(key) {
      const dataSource = [...this.model.eneDeviceLowers]
      this.model.eneDeviceLowers = dataSource.filter(item => item.id !== key)
    },

    handleAdd() {
      this.count++
      if (this.model.eneDeviceLowers && this.model.eneDeviceLowers.length > 0) {
        this.model.eneDeviceLowers.push({
          id: this.count,
          deviceId: '',
          deviceName: '',
          deviceProductId: '',
          deviceTypeId: '',
          deviceBrandId: '',
          devicePurchaseDate: '',
          acquisitionMethod: ''
        })
      } else {
        // this.model.eneDeviceLowers = [];
        this.$set(this.model, 'eneDeviceLowers', [])
        this.model.eneDeviceLowers.push({
          id: this.count,
          deviceId: '',
          deviceName: '',
          deviceProductId: '',
          deviceTypeId: '',
          deviceBrandId: '',
          devicePurchaseDate: '',
          acquisitionMethod: ''
        })
      }
      // console.log(1234,this.model)
      return this.model
    },
    onCellChange(record, name, value) {
      this.$set(record, name, value)
    },
    cellBlur(record, name, value) {
      // console.log(6688,value,record)
      this.$set(record, name, value)
    },
    add() {
      this.modelDefault.deviceBrandId = ''
      this.modelDefault.deviceProductId = ''
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      if (this.model.extendedTechnicalParameters?.length > 0) {
        // 使用已有数据
        this.extendedTechnicalParametersTable.dataSource = this.model.extendedTechnicalParameters;
      } else {
        // 初始化空行
        this.extendedTechnicalParametersTable.dataSource = [{ project: '', value: '' }];
      }
      this.visible = true;
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.model.extendedTechnicalParameters = [
            ...this.extendedTechnicalParametersTable.dataSource
          ]
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    deviceTypeChange(deviceTypeId) {
      let deviceType = this.$refs.treeSelect.treeDataFlat.filter(ts => ts.value === deviceTypeId)[0]
      if (deviceType && deviceType.parentId === '0') {
        setTimeout(() => {
          this.model.deviceTypeId = null
          this.model.treeValue = ''
          this.model.deviceBrandId = ''
        }, 50)
        return
      }
      this.model.deviceBrandId = this.$refs.treeSelect.treeDataFlat.filter(
        ts => ts.value === deviceType.parentId
      )[0].title
    },
    lowerDeviceTypeChange(record) {
      console.log("record.deviceTypeId:", record.deviceTypeId)
      getAction(this.url.getBrandId,{id:record.deviceTypeId}).then(
        res => {
          if (res.success) {
            this.$set(record, 'deviceBrandId', res.result)
          }
        }
      )
    },
    deviceIdChange(e) {
      iotHttpAction(`/device/instance/${this.model.deviceId}/detail`, null, 'GET').then(data => {
        this.model.deviceProductId = data.result.productName
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .ant-form {
  .mark-infos {
    position: relative;

    .editable-add-btn {
      position: absolute;
      top: 10px;
      right: 18px;
      z-index: 202;
    }

    .j-table-force-nowrap {
      height: 100%;

      .ant-table {
        height: 100%;

        .ant-table-body {
          overflow-y: auto;
        }

        .editable-cell {
          height: 33px;
        }

        .ant-table-bordered .ant-table-thead > tr > th, .ant-table-bordered .ant-table-tbody > tr > td {
          border-right: 0;
        }

        .ant-table-hide-scrollbar {
          border-right: 1px solid #e8e8e8;
        }
      }
    }
  }
}
</style>
